package com.bp.hearthealth.pulse.lnapps.bp_ui.bp_fragment.bp_tracker.blood_pressure

import androidx.databinding.ObservableField
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.liveData
import androidx.lifecycle.switchMap
import androidx.lifecycle.viewModelScope
import com.bp.hearthealth.pulse.lnapps.bp_utils.Constants
import com.bp.hearthealth.pulse.lnapps.base.BpBaseViewModel
import com.bp.hearthealth.pulse.lnapps.bp_extension.LogUtil
import com.bp.hearthealth.pulse.lnapps.bp_ui.bp_fragment.bp_tracker.bp_bean.BpBloodPressureAverageValues
import com.bp.hearthealth.pulse.lnapps.bp_ui.bp_fragment.bp_tracker.bp_bean.BpBloodPressureFilter
import com.bp.hearthealth.pulse.lnapps.bp_utils.DateUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.launch

class BloodPressureViewModel(private val repository: BloodPressureRepository) : BpBaseViewModel() {

    var firstText = MutableLiveData<String>()
    var secondText = MutableLiveData<String>()
    var thirdText = MutableLiveData<String>()
    var firstUrl = MutableLiveData<String>()
    var secondUrl = MutableLiveData<String>()
    var thirdUrl = MutableLiveData<String>()

    val listSize = ObservableField<Int>()

    //默认查进30天的数据
    val startTime = MutableLiveData(DateUtils.thirtyDaysAgoStartTimestamp())
    val endTime = MutableLiveData(DateUtils.getStartAndEndOfTodayTimestamps().second)
    var dataBean = MutableLiveData<DateRequestParam>()

    //    val selectedTime = MutableLiveData(
//        DateUtils.timestampToDate(
//            DateUtils.thirtyDaysAgoStartTimestamp(), Constants.TIME_STYLE
//        ) + "-" + DateUtils.timestampToDate(
//            System.currentTimeMillis(), Constants.TIME_STYLE
//        )
//    )
    val selectedTime = ObservableField(
        DateUtils.timestampToDate(
            DateUtils.thirtyDaysAgoStartTimestamp(), Constants.TIME_STYLE
        ) + "-" + DateUtils.timestampToDate(
            System.currentTimeMillis(), Constants.TIME_STYLE
        )
    )


    class DateRequestParam(val userId: String, val startTime: Long, val endTime: Long)

    /**
     * 查询指定时间范围内的数据
     */
    fun getBloodPressureDataForDateRange(userId: String) {
        dataBean.value = DateRequestParam(
            userId, startTime.value!!.toLong(), endTime.value!!.toLong()
        )
    }

    val queueBloodPressureData = dataBean.switchMap {
        liveData {
            val result = try {
                val code = repository.getBloodPressureForDateRange(
                    Constants.USER_ID, dataBean.value!!.startTime, dataBean.value!!.endTime
                )
                Result.success(code)
            } catch (e: Exception) {
                Result.failure(e)
            }
            emit(result)
        }
    }

    private val userId = MutableLiveData<String>()

    fun getAllBloodPressure(id: String) {
        userId.value = id
    }

    val bloodPressureList = userId.switchMap {
        liveData {
            val result = try {
                val code = repository.getBloodPressureByUserId(userId.value!!)
                Result.success(code)
            } catch (e: Exception) {
                Result.failure(e)
            }
            emit(result)
        }
    }
    private val lastThreeBloodPressureData = MutableLiveData<String>()

    fun getLast3BloodPressureData(id: String) {
        lastThreeBloodPressureData.value = id
    }

    val lastThreeData = lastThreeBloodPressureData.switchMap {
        liveData {
            val result = try {
                val code =
                    repository.getLastThreeBloodPressureData(lastThreeBloodPressureData.value!!)
                Result.success(code)
            } catch (e: Exception) {
                Result.failure(e)
            }
            emit(result)
        }
    }

    val filfter = MutableLiveData<HashMap<BpBloodPressureFilter, BpBloodPressureAverageValues>>()
    fun getFilterData(userId: String) {
        viewModelScope.launch(Dispatchers.Main) {
            try {
                val valueMap = HashMap<BpBloodPressureFilter, BpBloodPressureAverageValues>()
                valueMap[BpBloodPressureFilter.LATEST_DATA] =
                    async { repository.getLatestBloodPressureData(userId) }.await()!!
                valueMap[BpBloodPressureFilter.LATEST_24_HOURE_DATA] =
                    async { repository.getAverageValuesForLast24Hours(userId) }.await()!!
                valueMap[BpBloodPressureFilter.AVERAGE_DATA] =
                    async { repository.getAverageValuesForUser(userId) }.await()!!
                valueMap[BpBloodPressureFilter.MAX_DATA] =
                    async { repository.getMaxValuesForUser(userId) }.await()!!
                valueMap[BpBloodPressureFilter.MIN_DATA] =
                    async { repository.getMinValuesForUser(userId) }.await()!!
                filfter.value = valueMap
            } catch (e: Exception) {
                LogUtil.e(e)
            }
        }
    }

    //获取所有statusTypes
    val statusTypes = MutableLiveData<List<Int>?>()
    fun getStatisticsStateType(userId: String) {
        viewModelScope.launch(Dispatchers.Main) {
            statusTypes.value = repository.getStatusTypesByUserId(userId)
        }
    }


    //获取所有BloodPressureData
    private val allBloodPressureDataUserId = MutableLiveData<String>()
    fun getAllBloodPressureData(id: String) {
        allBloodPressureDataUserId.value = id
    }

    val allBloodPressureData = allBloodPressureDataUserId.switchMap {
        liveData {
            val result = try {
                val bloodPressureDataList =
                    repository.getBloodPressureDataByUserId(allBloodPressureDataUserId.value!!)
                Result.success(bloodPressureDataList)
            } catch (e: Exception) {
                Result.failure(e)
            }
            emit(result)
        }
    }


    class TodayRequestParam(val userId: String, val startTime: Long, val endTime: Long)

    //默认查询当前天的数据
    private val todayValue = MutableLiveData<TodayRequestParam>()

    fun getTodayList(userId: String) {
        todayValue.value = TodayRequestParam(
            userId,
            DateUtils.getStartAndEndOfTodayTimestamps().first,
            DateUtils.getStartAndEndOfTodayTimestamps().second
        )
    }

    val todayListResult = todayValue.switchMap {
        liveData {
            val result = try {
                val bloodPressureDataList = repository.getTodayBloodPressureData(
                    todayValue.value!!.userId,
                    todayValue.value!!.startTime,
                    todayValue.value!!.endTime
                )
                Result.success(bloodPressureDataList)
            } catch (e: Exception) {
                Result.failure(e)
            }
            emit(result)
        }
    }
}